import React from 'react';
import { connect } from 'dva';
import { Table, Button, Icon, message, Modal } from 'antd';
import _ from 'lodash';
import { routerRedux, Link } from 'dva/router';
import { col } from './col';
import { Filters } from './filters';
import LocModal from './modal';

const styles = require('../app.less');
const ownStyles = require('./index.css');

const confirm = Modal.confirm;
const columns = col.map((item) => {
  return _.merge(item, { key: item.dataIndex });
});

/**
 * TODO: 不用权限的人看到不同的界面
 * TODO: 错误处理，异常处理
 */
class Location extends React.Component {
  constructor(p) {
    super(p);
    // 函数绑定
    this.handleChange = this.handleChange.bind(this); // 搜索项变化
    this.handelSearch = this.handelSearch.bind(this); // 搜索
    this.clearSearch = this.clearSearch.bind(this); // 清除搜索
    this.handlePage = this.handlePage.bind(this); // 翻页
    this.handleDelete = this.handleDelete.bind(this); // 删除
    this.action = this.action.bind(this); // 新建或编辑

    const { location } = this.props;
    const { query } = location;
    // 当前页面的url: pathname + search
    // 用于新增或者编辑界面返回时候用的
    this.theUrl = window.btoa(location.pathname + location.search);
    this.state = {
      query: {
        wid: query.wid,
        area: query.area,
        floor: query.floor,
        therow: query.therow,
        thecolumn: query.thecolumn,
        offset: query.offset || 1,
        limit: 10,
      },
      modalType: '', // 用于控制显示编辑或者新建Modal
      item: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    // 查询所有的库位
    dispatch({
      type: 'warehouseLoc/query',
      payload: this.state.query,
    });
  }

  getOp() {
    const { defaultWid } = this.props.warehouseLoc;
    const { location } = this.props;
    return {
      key: 'op',
      title: '操作',
      render: (record) => {
        return (
          <div>
            <a>查看</a>
            {
              (
                !location.query.wid ||
                String(defaultWid) === String(location.query.wid)
              )
              && (
                [
                  <span>&nbsp;|&nbsp;</span>,
                  <Link onClick={this.action('edit', record)}>
                    编辑
                  </Link>,
                  <span>
                    &nbsp;|&nbsp;
                  </span>,
                  <a onClick={this.handleDelete(record.wlid)} color="red">删除</a>,
                ]
              )
            }
          </div>
        );
      },
    };
  }

  handleChange(value) {
    _.merge(this.state.query, value);
    this.setState({});
  }

  handlePage(page) {
    this.state.query.offset = page;
    this.handelSearch();
  }

  handleDelete(wlid) {
    return () => {
      const { dispatch } = this.props;
      confirm({
        title: '警告',
        content: '确认删除？删除后将不可恢复',
        onOk: () => {
          return new Promise((resolve, reject) => {
            dispatch({
              type: 'warehouseLoc/del',
              payload: {
                wlid,
                onEnd: (err) => {
                  if (err) {
                    reject(err);
                    return message.error(`删除失败${err.message}` || err);
                  }
                  message.success('删除成功');
                  resolve();
                  this.handelSearch();
                },
              },
            });
          });
        },
      });
    };
  }

  // 处理搜索按钮
  handelSearch() {
    const { dispatch, location } = this.props;
    location.query = _.merge(location.query, this.state.query);
    dispatch(routerRedux.push(location));
    dispatch({
      type: 'warehouseLoc/query',
      payload: location.query,
    });
  }

  clearSearch() {
    this.state.query = {};
    this.setState({});
    const { dispatch, location } = this.props;
    location.query = {};
    dispatch(routerRedux.push(location));
  }

  action(type, item = {}) {
    return () => {
      this.setState({
        modalType: type,
        item,
      });
      if (!type) {
        this.componentDidMount();
      }
    };
  }

  render() {
    const { warehouseLocs, total } = this.props.warehouseLoc;
    const { effects } = this.props.loading;
    const { query } = this.state;
    // 插入操作栏
    if (!columns.find(item => item.key === 'op')) {
      columns.push(this.getOp.bind(this)());
    } else {
      columns.pop();
      columns.push(this.getOp.bind(this)());
    }

    return (
      <div className={styles.container}>
        {
          // 上下结构，上面用来做筛选条件
          // 下面用来做表格显示
          /**
           * 筛选条件按照:
           *  仓库 => 库区 => 楼层 => 行，列 往下走
           */
        }
        {
          Boolean(this.state.modalType) &&
            <LocModal
              visible={Boolean(this.state.modalType)}
              data={this.state.item}
              onFinish={this.action('')}
              type={this.state.modalType}
            />
        }
        <div className={ownStyles.filter}>
          <h3>筛选：</h3>
          <Filters query={query} onChange={this.handleChange} />
          <br />
          <Button
            type="primary"
            onClick={this.handelSearch}
            loading={effects['warehouseLoc/query']}
          >
            <Icon type="search" /> 查询
          </Button>
          &nbsp;&nbsp;
          <Button
            type="danger"
            onClick={this.clearSearch}
          >
            清空
          </Button>
        </div>
        <div>
          <h3>库位操作：</h3>
          <Button
            type="primary"
            onClick={this.action('create')}
          >
            <Icon type="plus" /> 新建库位
          </Button>
        </div>
        <br />
        <div>
          <h3>库位列表：</h3>
          <Table
            loading={effects['warehouseLoc/query']}
            columns={columns}
            dataSource={warehouseLocs}
            pagination={{
              total: Number(total),
              current: Number(query.offset),
              pageSize: 10,
              onChange: this.handlePage,
            }}
          />
        </div>
      </div>
    );
  }
}

export default connect(state => state)(Location);
